#include "logs.h"
#include <QFile>
#include <QTextStream>
#include <QDebug>

//处理回滚事件

Logs::Logs(QObject *parent) : QObject(parent)
{
    // 初始化日志文件
    m_logFileName = "logs.txt";
}

// 写入日志
void Logs::writeLog(const QString &message)
{
    QFile file(m_logFileName);
    if (file.open(QIODevice::WriteOnly | QIODevice::Append)) {
        QTextStream out(&file);
        out << message << "\n";
        file.close();
    } else {
        qWarning() << "Failed to open log file for writing.";
    }
}

// 撤回操作与回滚日志
void Logs::rollbackLog()
{
    QFile file(m_logFileName);
    if (file.open(QIODevice::ReadOnly)) {
        QTextStream in(&file);
        QStringList logEntries;
        while (!in.atEnd()) {
            QString operation = in.readLine();
            logEntries.append(operation);
        }
        file.close();

        if (logEntries.size() > 1) {
            // 移除最后一条日志
            logEntries.removeLast();
            // 重新写入日志文件
            if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
                QTextStream out(&file);
                foreach(const QString &logEntry, logEntries) {
                    out << logEntry << "\n";
                }
                file.close();
            } else {
                qWarning() << "Failed to open log file for writing.";
            }
        } else {
            qDebug() << "No log entries to rollback.";
        }
    } else {
        qWarning() << "Failed to open log file for reading.";
    }
}

// 设置日志文件名
void Logs::setLogFileName(const QString &fileName)
{
    m_logFileName = fileName;
}

// 获取日志文件名
QString Logs::logFileName() const
{
    return m_logFileName;
}
